/******************************************************************************
** 
** Strip empty tail. 
** 
** File name:	strip_empty_tail.c
** Compilation:	cc strip_empty_tail.c -o strip_empty_tail
** Execution:	./strip_empty_tail
** 
** Description:
** Reads the input, divides it into strings, echoes the strings but without  
** spaces and tabs in the very end. Empty lines are not printed too.
** 
******************************************************************************/
#include <stdio.h>

#define MAX_LINE_LENGTH 1000
#define TAB_SYMBOL '\t'
#define SPACE_SYMBOL ' '

int get_line(char line[], int max_length);
int strip_spaces(char line[], int length);

int current_length, stripped_length;
char current_line[MAX_LINE_LENGTH];

int main()
{
    extern int current_length, stripped_length;
    extern char current_line[MAX_LINE_LENGTH];

    current_length = stripped_length = 0;
    while ((current_length = get_line(current_line, MAX_LINE_LENGTH)) != 0) {
        stripped_length = strip_spaces(current_line, current_length);
        if (stripped_length > 1) { // string was not only spaces
            printf("* Stripped (length is %d): %s\n", stripped_length, current_line);
        } else {
            printf("* Empty string!\n");
        }
    }

    return 0;
}


// get_line: Reads one line from the input and stores it in the array, returns line length.
int get_line(char line[], int max_length) {
    int c, i;

    for (i=0; i<max_length && (c=getchar()) != EOF && c != '\n'; ++i) {
        line[i] = c;
    }
    if (c == '\n') {
        line[i] = c;
        ++i;
    }
    line[i] = '\0';
    return i;
}


// strip_spaces: Returns new string length (with '\n' counted), '\0' must be put at [length] position of the source string.
int strip_spaces(char line[], int length) {
    
    --length; // minus '\0'
    --length; // minus '\n'
    while ((line[length] == '\t') || (line[length] == ' ')) {
        --length;
    }
    ++length; // plus for '\n'
    line[length] = '\n';
    ++length; // plus for '\0'
    line[length] = '\0';
    
    return length;
}